package patrol.mobile.com.mobilepatrol.activity.yanghuke.zuoyeshangbao;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.LocationHelper;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.office.AdviceDetailActivity;
import patrol.mobile.com.mobilepatrol.activity.yanghuke.zuoyeshangbao.bean.ZuoYeBean;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DateBean;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.utils.CommonParamsHelper;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.DatePickerUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.StringUtils;
import patrol.mobile.com.mobilepatrol.utils.TimeUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.view.CallBack;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

/**
 * Created by z on 2018/9/13.
 * Des: 现场安全布放
 */

public class XcaqBfActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    private static final String TAG = "AAAAAA";
    @BindView(R.id.mEditPxr)
    EditText mEditPxr;
    @BindView(R.id.mEditPxsj)
    TextView mEditPxsj;
    @BindView(R.id.mEditPxnr)
    EditText mEditPxnr;
    @BindView(R.id.mEditPxrs)
    EditText mEditPxrs;
    @BindView(R.id.shiRadioButton)
    RadioButton shiRadioButton;
    @BindView(R.id.fouRadioButton)
    RadioButton fouRadioButton;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private static final String ADVICE_ID = "ADVICE_ID";
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    private int limitSize = 4;
    String isChecked = "否";
    String mainId;
    private List<String> imgUUIDs = new ArrayList<>();
    private List<DeviceDetailImgBean> deviceDetailImgBeans;
    private ZuoYeBean.YhkOperationAreaLayListBean yhkOperationAreaLayListBean;
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();
    private List<String> imgOldUUIDs = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_xcaqbf_layout;
    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
        super.initTitle();
        yhkOperationAreaLayListBean = (ZuoYeBean.YhkOperationAreaLayListBean) getIntent().getSerializableExtra("yhkOperationAreaLayListBean");
        mainId = getIntent().getStringExtra("id");
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("现场安全布设");
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(v -> finish());
        location(false);
        mEditPxnr.setOnClickListener(v -> {
            ToastUtils.showToast("正在定位!");
            location(true);
        });
        if (yhkOperationAreaLayListBean != null) {
            mEditPxr.setText(yhkOperationAreaLayListBean.getSitePerson());
            mEditPxsj.setText(yhkOperationAreaLayListBean.getLayDate());
            mEditPxnr.setText(yhkOperationAreaLayListBean.getLocation());
            mEditPxrs.setText(yhkOperationAreaLayListBean.getSituation());
            if (yhkOperationAreaLayListBean.getYes().equals("是")) {
                shiRadioButton.setChecked(true);
            } else {
                fouRadioButton.setChecked(true);
            }
        } else {
            btnSubmit.setVisibility(View.VISIBLE);
        }
        getHttpData();
        mEditPxsj.setText(TimeUtils.timeString(System.currentTimeMillis()));
        mEditPxsj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerUtil.getInstance(v.getContext()).setCallBack(new CallBack<DateBean>() {
                    @Override
                    public void onBack(DateBean dateBean) {
                        mEditPxsj.setText(dateBean.getmDate());
                    }
                });
            }
        });
    }

    double lat = 0;
    double lon = 0;

    private void location(boolean b) {
        LocationHelper.getLocation(new LocationHelper.MyLocationListener() {
            @Override
            public void result(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        lat = amapLocation.getLatitude();//获取纬度
                        lon = amapLocation.getLongitude();//获取经度
                        amapLocation.getAccuracy();//获取精度信息
                        Log.e("location", lat + "" + lon);
                        if (b || mEditPxnr.getText().toString().length() == 0)
                            mEditPxnr.setText("经度:" + lat + " 纬度:" + lon);
                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }

            }
        });
    }

    private void getHttpData() {
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("id", mainId);
        HttpSender sender = new HttpSender(this, baseUrl, Urls.getYhkOperationAreaLayEntity);
        sender.requestPost(hashMap, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {
                deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                selImageList = new ArrayList<>();
                adapter = new ImagePickerAdapter(XcaqBfActivity.this, selImageList, limitSize);
                adapter.setOnItemClickListener(XcaqBfActivity.this);
                recyclerView.setLayoutManager(new GridLayoutManager(XcaqBfActivity.this, limitSize));
                recyclerView.setHasFixedSize(true);
                recyclerView.setAdapter(adapter);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(XcaqBfActivity.this);

                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");

                    long currentTime = System.currentTimeMillis();
                    fileHelper.savePicture(currentTime + ".jpg", replace);
                    ImageItem imageItem = new ImageItem();
                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                    try {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                        imageItem.path = filePath;
//                        Glide.with(AdviceDetail2Activity.this).load(new File(filePath)).into(iv);
                        selImageList.add(imageItem);
                        imgOldUUIDs.add(deviceDetailImgBean.getId());
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        oldImgInfo.add(upImgInfoBean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });
//                try {
//                    imageBeans = GsonUtil.gsonToList(attachList, ImageBean.class);
//                    List<ImageItem> imageItems = new ArrayList<>();
//                    for (ImageBean imageBean : imageBeans) {
//                        ImageItem imageItem = new ImageItem();
//                        imageItem.path = baseUrl + (imageBean.getFilePath().replace("\\", "/"));
//                    }
//                    adapter.setImages(imageItems);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case AdviceDetailActivity.IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(view.getContext(), ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(view.getContext(), ImageGridActivity.class);
                                startActivityForResult(intent1, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, AdviceDetailActivity.REQUEST_CODE_PREVIEW);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    ArrayList<ImageItem> images;
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
            }
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        submit();
    }

    private void submit() {
        final HttpSender sender = new HttpSender(this, baseUrl, Urls.yhkOperationAreaLayUploadData);
        String pxr = CommonUtil.getText(mEditPxr);
        String pxsj = CommonUtil.getText(mEditPxsj);
        String pxnr = CommonUtil.getText(mEditPxnr);
        String pxrs = CommonUtil.getText(mEditPxrs);
        if (StringUtils.isEmpty(pxr) || StringUtils.isEmpty(pxsj) || StringUtils.isEmpty(pxnr) || StringUtils.isEmpty(pxrs)) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (radioGroup.getCheckedRadioButtonId() == R.id.shiRadioButton) {
                    isChecked = "是";
                } else {
                    isChecked = "否";
                }
            }
        });
        HashMap<String, String> idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();
        if (yhkOperationAreaLayListBean == null || yhkOperationAreaLayListBean != null && yhkOperationAreaLayListBean.getId() == null) {//            idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();
        }else {
            idDateBmnameMap.put("id", yhkOperationAreaLayListBean.getId());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("sitePerson", pxr);
        map.put("layDate", pxsj);
        map.put("location", pxnr);
        map.put("situation", pxrs);
        map.put("mainId", mainId);
        map.put("yes", isChecked);
        map.put("olat", lat);//经度
        map.put("olng", lon);//纬度
        map.putAll(idDateBmnameMap);
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("yhkOperationAreaLay", GsonUtil.map2Json(map));
        // TODO: 2018/10/23
        List<ImageItem> images = adapter.getImages();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
        for (ImageItem image : images) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("yhkOperationAreaLay");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        map1.put("sysAttachmentsJson", GsonUtil.bean2Json(upImgInfoBeanList));
        Log.i(TAG, "submit: " + GsonUtil.map2Json(map1));
        showLoading();
        sender.postJson(GsonUtil.map2Json(map1), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i(TAG, "onResponse: " + e.toString());
                hideLoading();
                Toast.makeText(XcaqBfActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "onResponse: " + response);
                hideLoading();
//                finish();
                upImg();
            }
        });
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            for (ImageItem imageItem : selImageList) {
                File file = new File(imageItem.path);
                list.add(file);
            }
            List<Map<String, String>> params = new ArrayList<>();
            for (String imgUUID : imgUUIDs) {
                Map<String, String> map = new HashMap<>();
                map.put("id", imgUUID);
                map.put("type", "yhkOperationAreaLay");
                params.add(map);
            }
            LuBanHelper luBanHelper = new LuBanHelper(XcaqBfActivity.this, list, params);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.i(TAG, "onResponse: " + e);
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.i(TAG, "onResponse: " + response);
                    Toast.makeText(XcaqBfActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        }
    }

    ArrayList<ImageItem> images = null;
}
